document.body.onload = gameInit;

function gameInit() {
    var WEIGHT_LOAD_IMAGE = 2;
    var cvs1, cvs2, ctx1, ctx2, cvsWidth, cvsHeight;
    var lastTime, deltaTime;
    var bgPic = new Image();
    var background = new background();
    var ane = new aneObj();
    var fruit = new fruitObj();
    var mom = new momObj();
    var baby = new babyObj();
    var load = new gameLoad();
    init();
    lastTime = Date.now();
    deltaTime = 0;
    gameLoop();

    function init() {
        //加载进程开始
        load.init();

        load.add('newCanvas');
        //get main canvas
        cvs1 = document.getElementById('canvas1');
        ctx1 = cvs1.getContext('2d');

        //get bg canvas
        cvs2 = document.getElementById('canvas2');
        ctx2 = cvs2.getContext('2d');
        load.complete('newCanvas');

        //get bg img
        bgPic.src = './src/background.jpg';
        load.getImage('background', bgPic);

        //get width height
        cvsWidth = cvs1.width;
        cvsHeight = cvs1.height;

        ane.init();
        fruit.init();
        mom.init();
        baby.init();
    }

    function gameLoop() {
        requestAnimFrame(gameLoop); //FPS:frame per second
        var now = Date.now();
        deltaTime = now - lastTime;
        lastTime = now;
        //console.log(deltaTime);

        background.draw();
        if (load.loadStatus) { //加载中
            load.draw();
        } else {
            ane.draw();
            fruit.draw();
            ctx1.clearRect(0, 0, cvsWidth, cvsHeight);
            mom.draw();
            baby.draw();
        }
    }

    function gameLoad() {
        var width = 200,
            height = 20,
            r = 100;
        var loadObj;
        var timeHander;
        this.init = function() {
            this.loadStatus = true;
            this.num = 0;
            this.ok = 0;
            this.total = 0;
            this.solve = 0;
            loadObj = {};
        };
        this.add = function(text, weight) {
            console.log(text);
            weight = weight || 1;
            this.total += weight;
            if (text in loadObj) {
                loadObj[text] += weight;
            } else {
                this.num++;
                loadObj[text] = weight;
            }
            if(timeHander){
                clearInterval(timeHander);
            }
            return this.total;
        };
        this.getImage = function(text, img, bit) {
            this.add(text, bit || WEIGHT_LOAD_IMAGE);
            img.onload = function() {
                load.complete(text);
            };
        };
        this.complete = function(text, weight) {
            var right = loadObj[text];
            if (weight == undefined || weight == right) {
                weight = right;
                this.num--;
                this.solve += weight
                delete loadObj[text];
                console.log('%c' + text, 'color:red');
                if(this.total <= this.solve){
                    timeHander = setTimeout(function(){
                        load.loadStatus = false;
                    }, 500);
                }else if(timeHander){
                    clearInterval(timeHander);
                }
                return true;
            } else if (weight < right) {
                this.solve += weight
                loadObj[text] = right - weight;
                return true;
            } else {
                return false;
            }
        };
        this.draw = function() {
            ctx2.save();
            ctx2.strokeStyle = "white";
            ctx2.lineWidth = 20;
            ctx2.beginPath();
            //ctx2.lineCap = 'round';
            ctx2.arc(cvsWidth >> 1, cvsHeight >> 1, r, 0, Math.PI * 2, true);
            //ctx2.closePath();
            ctx2.stroke();
            ctx2.lineWidth = 1;
            ctx2.font = "24px Courier New";
            ctx2.strokeText('加载中...', (cvsWidth >> 1) - 50, cvsHeight >> 1);

            //进度
            ctx2.strokeStyle = "red";
            ctx2.lineWidth = 10;
            ctx2.beginPath();
            ctx2.arc(cvsWidth >> 1, cvsHeight >> 1, r, 0, Math.PI * 2 * (this.solve / this.total), true);
            console.log('加载进度--------'+(this.solve / this.total));
            ctx2.stroke();
            ctx2.restore();
        };
    }

    function background() {
        function draw() {
            ctx2.drawImage(bgPic, 0, 0, cvsWidth, cvsHeight);
        }

        return {
            draw: draw
        };
    }

    function aneObj(num) {
        var x = [];
        var y = [];
        var len = [];

        num = num || 50;

        function init() {
            for (var i = 0; i < num; i++) {
                x[i] = i * 16 + Math.random() * 28;
                len[i] = 200 + Math.random() * 50;
            }
        }

        function draw() {
            ctx2.save();
            ctx2.globalAlpha = 0.4;
            ctx2.strokeStyle = "#3b1541";
            ctx2.lineCap = 'round';
            ctx2.lineWidth = 10;
            ctx2.beginPath();
            for (var i = 0; i < num; i++) {
                ctx2.moveTo(x[i], cvsHeight);
                ctx2.lineTo(x[i], cvsHeight - len[i]);
            }
            ctx2.stroke();
            ctx2.restore();
        }

        return {
            init: init,
            draw: draw
        };
    }

    function fruitObj(num) {
        var alive = []; //bool
        var orange = new Image();
        var blue = new Image();

        num = num || 30;

        function init() {
            for (var i = 0; i < num; i++) {
                alive[i] = false;
            }
            orange.src = './src/fruit.png';
            blue.src = './src/blue.png';
            load.getImage('fruitOranger', orange);
            load.getImage('fruitBlue', blue);
        }

        function draw() {

        }

        function born() {
            var id = Math.floor(Math.random() * ane.num);
            var x = ane.x[id];
            var y = cvsHeight - ane.len[id];
        }
        return {
            init: init,
            draw: draw,
            born: born
        };
    }

    function momObj() {
        var r,
            body = new Image(),
            tail = new Image(),
            eye = new Image(),
            targetX, targetY;
        var bodyImages = [], bodyLength = 8, bodyCur = 0,
            tailImages = [], tailLength = 8, tailCur = 0,
            eyeImages = [], eyeLength = 2, eyeCur = 0;

        this.x = 0;
        this.y = 0;
        this.init = function() {
            this.x = cvsWidth >> 1;
            this.y = cvsHeight >> 1;
            targetX = this.x;
            targetY = this.y;
            r = 0;

            body.src = './src/bigSwim0.png';


            load.getImage('momBody', body);
            //尾巴
            for(var i=0;i<tailLength;i++){
                tailImages[i] = new Image();
                tail = tailImages[i];
                tail.src = './src/bigTail'+i+'.png';
                load.getImage('momTail'+i, tail);
            }
            //眼睛
            for(var i=0;i<eyeLength;i++){
                eyeImages[i] = new Image();
                eye = eyeImages[i];
                eye.src = './src/bigEye'+i+'.png';
                load.getImage('momEye'+i, eye);
            }
            //注册事件
            if (typeof addEventListener == 'undefined') {
                cvs1.attachEvent('onmousemove', mouseMove);
            } else {
                cvs1.addEventListener('mousemove', mouseMove, false);
            }
        }

        function mouseMove(e) {
            targetX = e.offSetX || e.layerX || 0;
            targetY = e.offSetY || e.layerY || 0;
        }

        this.draw = function() {
            //位置
            this.x = lerpDistance(targetX, this.x, .98);
            this.y = lerpDistance(targetY, this.y, .98);
            //方向
            var beta = Math.atan2(this.y - targetY, this.x - targetX);
            r = lerpAngle(beta, r, 0.6);
            //动画
            tail = tailImages[tailCur];
            if(tailCur == 7){
                tailCur = 0;
            }else{
                tailCur++;
            }
            eye = eyeImages[eyeCur%191 < 3?1:0];
            if(eyeCur == 10000){
                eyeCur = 0;
            }else{
                eyeCur++;
            }
            ctx1.save();
            ctx1.translate(this.x, this.y);
            ctx1.rotate(r);
            ctx1.drawImage(body, -(body.width >> 1), -(body.height >> 1));
            ctx1.drawImage(tail, -(tail.width >> 1) + 29, -(tail.height >> 1));
            ctx1.drawImage(eye, -(eye.width >> 1), -(eye.height >> 1));
            ctx1.restore();
        }
    }

    function babyObj() {
        var x, y, r,
            body = new Image(),
            tail = new Image(),
            eye = new Image();
        var bodyImages = [], bodyLength = 8, bodyCur = 0,
            tailImages = [], tailLength = 2, tailCur = 0,
            eyeImages = [], eyeLength = 2, eyeCur = 0;

        function init() {
            x = cvsWidth >> 1;
            y = cvsHeight >> 1;
            r = 0;
            body.src = './src/baby.png';
            load.getImage('babyBody', body);

            //尾巴
            for(var i=0;i<tailLength;i++){
                tailImages[i] = new Image();
                tail = tailImages[i];
                tail.src = './src/babyTail'+i+'.png';
                load.getImage('babyTail'+i, tail);
            }
            //眼睛
            for(var i=0;i<eyeLength;i++){
                eyeImages[i] = new Image();
                eye = eyeImages[i];
                eye.src = './src/bigEye'+i+'.png';
                load.getImage('babyEye'+i, eye);
            }
        }

        function draw() {
            var mx = mom.x;
            var my = mom.y;
            x = lerpDistance(mx, x, .98);
            y = lerpDistance(my, y, .98);
            var beta = Math.atan2(y - my, x - mx);
            r = lerpAngle(beta, r, 0.8);
            //动画
            tail = tailImages[tailCur];
            if(tailCur == 1){
                tailCur = 0;
            }else{
                tailCur++;
            }
            eye = eyeImages[eyeCur%131 < 3?1:0];
            if(eyeCur == 10000){
                eyeCur = 0;
            }else{
                eyeCur++;
            }
            ctx1.save();
            ctx1.translate(x, y);
            ctx1.rotate(r);
            ctx1.drawImage(body, -(body.width >> 1), -(body.height >> 1));
            ctx1.drawImage(tail, -(tail.width >> 1) + 25, -(tail.height >> 1));
            ctx1.drawImage(eye, -(eye.width >> 1), -(eye.height >> 1));
            ctx1.restore();
        }

        return {
            init: init,
            draw: draw
        };
    }
}